package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Transactional
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = Dish.builder()
                .id(dishDTO.getId())
                .name(dishDTO.getName())
                .categoryId(dishDTO.getCategoryId())
                .price(dishDTO.getPrice())
                .image(dishDTO.getImage())
                .description(dishDTO.getDescription())
                .status(dishDTO.getStatus())
                .build();

        dishMapper.insert(dish);

        log.info("菜品主键回写：dishId ={}", dish.getId());

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            for (DishFlavor f : flavors) {
                f.setDishId(dish.getId());
            }

            dishFlavorMapper.insertBatch(flavors);
        }

    }


    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {

        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());

        Page<DishVO> dishVO = dishMapper.select(dishPageQueryDTO);

        long total = dishVO.getTotal();
        List<DishVO> result = dishVO.getResult();

        return new PageResult(total,result);


    }

    /**
     * 删除菜品和口味
     * @param ids
     */
    @Transactional
    @Override
    public void deleteDishAndFlavor(List<Long> ids) {
        //判断菜品是否在售
        for (Long id : ids) {
            DishVO byId = dishMapper.getById(id);
            if(byId.getStatus() == StatusConstant.ENABLE)
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        //判断这些菜品是否在套餐中
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && !setmealIds.isEmpty()) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        for (Long id : ids) {
            dishMapper.deleteById(id);
            dishFlavorMapper.deleteByDishId(id);
        }
    }

    @Transactional
    @Override
    public DishVO getById(Long id) {
        DishVO dishVO = dishMapper.getById(id);
        List<DishFlavor> list = dishFlavorMapper.getByDishId(id);

        dishVO.setFlavors(list);
        return dishVO;
    }

    @Override
    public void updateDishAndFlavor(DishVO dishVO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishVO,dish);
        dishMapper.update(dish);
        List<DishFlavor> flavors = dishVO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            dishFlavorMapper.deleteByDishId(dishVO.getId());

            //stream流处理
            flavors.stream().map(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
                return dishFlavor;
            }).collect(Collectors.toList());
//            for (DishFlavor f : flavors) {
//                f.setDishId(dish.getId());
//            }
        }
        dishFlavorMapper.insertBatch(flavors);
    }

    @Override
    public List<DishVO> getByCategoryId(Long categoryId) {
        List<DishVO> listDishVO =  dishMapper.getByCategoryId(categoryId);
        listDishVO.stream().forEach(dishVO -> {
            dishVO.setFlavors(dishFlavorMapper.getByDishId(dishVO.getId()));
        });
        return listDishVO;
    }

    @Override
    public List<DishVO> getByCategoryIdAndStatus(Dish dish) {
        List<DishVO> listDishVO =  dishMapper.getByCategoryIdAndStatus(dish);
        listDishVO.stream().forEach(dishVO -> {
            dishVO.setFlavors(dishFlavorMapper.getByDishId(dishVO.getId()));
        });
        return listDishVO;
    }

    @Override
    public void startOrStop(Dish dish) {
        dishMapper.updateStatus(dish);
    }

}
